import { FC, useState, useEffect, useCallback } from 'react';
import {
  Layout,
  Card,
  Space,
  Button,
  Row,
  Col,
  Table,
  message,
  Tag,
  Tooltip,
} from 'antd';
import dayjs from 'dayjs';
import {
  DownloadOutlined,
  CalendarOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { phaseSummaryApi } from 'services/phase-summary';
import { ListParams, PhaseSummaryItem } from 'types/phase-summary';
import { downloadFile, MIME_TYPES } from 'utils/download';
import MainLayout from 'components/MainLayout';
import styles from './index.module.css';

// 报告类型
const REPORT_TYPES = [
  { key: 1, label: '月度报告' },
  { key: 2, label: '季度报告' },
  { key: 3, label: '年度报告' },
];

// 报告版本
const REPORT_VERSIONS = [
  { key: 1, label: '决策版' },
  { key: 2, label: '创新版' },
  { key: 3, label: '科研版' },
];

// 产业方向
const INDUSTRIES = [
  { key: 'agriculture', label: '大农业' },
  { key: 'equipment', label: '大装备' },
  { key: 'bigdata', label: '大数据' },
  { key: 'newmaterial', label: '新材料' },
  { key: 'newenergy', label: '新能源' },
  { key: 'medicine', label: '新医药' },
  { key: 'optoelectronic', label: '光电信息' },
  { key: 'ginseng', label: '人参' },
  { key: 'quantum', label: '量子技术' },
  { key: 'ai', label: '人工智能' },
];

const PhaseSummary: FC = () => {
  const [selectedType, setSelectedType] = useState<number>(1);
  const [selectedVersion, setSelectedVersion] = useState<number>(1);
  const [selectedIndustry, setSelectedIndustry] = useState<string>('');
  const [phaseSummaries, setPhaseSummaries] = useState<PhaseSummaryItem[]>([]);
  const [loading, setLoading] = useState(false);
  // 添加分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 模拟获取报告列表
  const fetchPhaseSummaries = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const params: ListParams = {
          page,
          pageSize,
          report_type: selectedType,
          report_style: selectedVersion,
          workflow_name: 1, // 1是阶段总结
        };

        if (selectedIndustry) {
          params.industry = selectedIndustry;
        }

        const res = await phaseSummaryApi.getSummaryList(params);

        if (res.code === 200) {
          setPhaseSummaries(res.data.results);
          setPagination((prev) => ({
            ...prev,
            current: page,
            total: res.data.count,
          }));
        }
      } catch (error) {
        message.error('获取阶段报告失败');
      } finally {
        setLoading(false);
      }
    },
    [selectedType, selectedVersion, selectedIndustry]
  );

  // 当选择的类型、版本或产业改变时，重新获取阶段总结报告列表
  useEffect(() => {
    fetchPhaseSummaries(1, pagination.pageSize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedType, selectedVersion, selectedIndustry]);

  const handleDownload = async (report: any) => {
    try {
      const response = await phaseSummaryApi.downloadSummaryReport(report.id);

      // 检查返回的数据类型和内容
      console.log('响应类型:', typeof response);
      console.log('是否是Blob:', response instanceof Blob);

      downloadFile(
        response,
        `${report.title || '阶段总结报告'}.docx`,
        MIME_TYPES.WORD
      );
    } catch (error) {
      message.error('下载失败');
      console.error('下载失败:', error);
    }
  };

  const columns: ColumnsType<PhaseSummaryItem> = [
    {
      title: '报告标题',
      dataIndex: 'title',
      key: 'title',
      render: (text) => (
        <Space>
          <FileTextOutlined style={{ color: '#1890ff' }} />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '报告类型',
      dataIndex: 'report_type',
      key: 'report_type',
      render: (type) => {
        if (type === 0) return '无';

        const typeInfo = REPORT_TYPES.find((t) => t.key === type);
        const colors = {
          1: 'blue',
          2: 'green',
          3: 'purple',
        };
        return (
          <Tag color={colors[type as keyof typeof colors]}>
            {typeInfo?.label}
          </Tag>
        );
      },
    },
    {
      title: '版本',
      dataIndex: 'report_style',
      key: 'report_style',
      render: (version) => {
        if (version === 0) return '无';

        const versionInfo = REPORT_VERSIONS.find((v) => v.key === version);
        const colors = {
          1: 'orange',
          2: 'cyan',
          3: 'geekblue',
        };
        return (
          <Tag color={colors[version as keyof typeof colors]}>
            {versionInfo?.label}
          </Tag>
        );
      },
    },
    {
      title: '产业方向',
      dataIndex: 'industry',
      key: 'industry',
      render: (industry) => {
        if (!industry) return '-';
        return <Tag color="magenta">{industry}</Tag>;
      },
    },
    {
      title: '生成时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time) => (
        <Space>
          <CalendarOutlined style={{ color: '#1890ff' }} />
          <span>{dayjs(time).format('YYYY-MM-DD HH:mm:ss')}</span>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Tooltip title="下载报告">
          <Button
            type="link"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
          >
            下载
          </Button>
        </Tooltip>
      ),
    },
  ];

  const { Sider } = Layout;

  return (
    <MainLayout>
      <Layout className={styles.layout}>
        <Sider width={250} className={styles.sider}>
          <Card title="阶段报告" bordered={false} style={{ height: '100%' }}>
            <div className={styles.reportTypes}>
              {REPORT_TYPES.map((type) => (
                <div key={type.key} className={styles.typeGroup}>
                  <h3>
                    <FileTextOutlined style={{ marginRight: 8 }} />
                    {type.label}
                  </h3>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    {REPORT_VERSIONS.map((version) => (
                      <Button
                        key={version.key}
                        type={
                          selectedType === type.key &&
                          selectedVersion === version.key
                            ? 'primary'
                            : 'default'
                        }
                        block
                        onClick={() => {
                          setSelectedType(type.key);
                          setSelectedVersion(version.key);
                        }}
                      >
                        {version.label}
                      </Button>
                    ))}
                  </Space>
                </div>
              ))}
            </div>
          </Card>
        </Sider>
        <Layout className={styles.content}>
          <Card bordered={false}>
            <div className={styles.industries}>
              <Row gutter={[8, 8]}>
                <Col span={4}>
                  <Button
                    type={selectedIndustry === '' ? 'primary' : 'default'}
                    onClick={() => setSelectedIndustry('')}
                    block
                  >
                    全部
                  </Button>
                </Col>
                {INDUSTRIES.map((industry) => (
                  <Col key={industry.key} span={4}>
                    <Button
                      type={
                        selectedIndustry === industry.label
                          ? 'primary'
                          : 'default'
                      }
                      onClick={() => setSelectedIndustry(industry.label)}
                      block
                    >
                      {industry.label}
                    </Button>
                  </Col>
                ))}
              </Row>
            </div>

            <Table<PhaseSummaryItem>
              className={styles.reportTable}
              columns={columns}
              dataSource={phaseSummaries}
              rowKey="id"
              loading={loading}
              pagination={{
                ...pagination,
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
                onChange: (page, pageSize) => {
                  fetchPhaseSummaries(page, pageSize);
                },
              }}
            />
          </Card>
        </Layout>
      </Layout>
    </MainLayout>
  );
};

export default PhaseSummary;
